<?php

use App\Models\Admin;
use App\Models\AdminAuth;
use App\Models\AdminToken;
use App\Models\Auth;

class Login
{
    public static $info;
    public static $login_type;
    public static $token_info;

    public static function check_admin_auth($auth_id = 0)
    {
        if (self::$info->admin_auth_id === -1) return 0;
        $auth = Auth::where('id', $auth_id)->where('status', 1)->where('del', 2)->first();
        if (!$auth) return 100016;
        if (self::$info->admin_auth_id === 0) {
            if ($auth->check_type !== 1) return 100016;
        } else {
            if ($auth->check_type === 1) return 0;
            $admin_auth = AdminAuth::select('id')
                ->where('id', self::$info->admin_auth_id)
                ->where('auth_ids', 'like', "%\"$auth_id\"%")
                ->where('del', 2)
                ->first();
            if (!$admin_auth) return 100016;
        }
        return 0;
    }

    public static function admin_check($auth_id = 0)
    {
        if (!request()->header('Authorization')) return 100003;
        $header_token_arr = explode('Bearer ', request()->header('Authorization'));
        if (!isset($header_token_arr[1])) return 100003;
        $header_token = $header_token_arr[1];
        if (!$header_token) return 100003;
        $admin_token_info = AdminToken::where('token', $header_token)->where('del', 2)->where('updated_at', '>', Lu::date(time() - (60 * 60 * 24 * 3)))->first();
        if (!$admin_token_info) return 100003;
        $admin_info = Admin::where('id', $admin_token_info->admin_id)->where('del', 2)->where('status', 1)->first();
        if (!$admin_info) return 100003;
        self::$info = $admin_info;
        self::$login_type = $admin_token_info->type;
        self::$token_info = $admin_token_info;
        $auth_check_res = self::check_admin_auth($auth_id);
        if ($auth_check_res !== 0) return $auth_check_res;
        $admin_token_info->updated_at = Lu::date();
        $admin_token_info->save();
        return 0;
    }

    public static function admin($auth_id = 0)
    {
        $check_res = self::admin_check($auth_id);
        if ($check_res !== 0) Yo::error_echo($check_res);
    }
}
